<template>
  <div class="main">
    <div class="mBottom-20 main_top">
      <div>
        <Button
          style="width: 45px; background-color: #40485b; color: #fff"
          class="mRight-10"
          @click="refresh"
          icon="md-refresh"
        >
        </Button>

        <Button type="primary" @click="DrawerStzte = true" v-if="pathData.includes('Renew:add')"
          >添加</Button
        >
      </div>

      <div style="display: flex">
        <Input
          class="mRight-10"
          search
          enter-button
          v-model="content"
          placeholder="输入功能内容关键字..."
          @on-search="findlist(1)"
        />
      </div>
    </div>

    <el-table
      :data="tableData.records"
      :style="{ maxWidth: tableWidth }"
      style="margin-bottom: 20px"
      row-key="id"
      border
      default-expand-all
    >
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="content" label="更新内容" />
      <el-table-column prop="turnoverTime" label="更新时间" width="200" />
      <el-table-column label="颜色" width="200">
        <template #default="scope">
          <Tag :color="scope.row.type">{{ scope.row.type }}</Tag>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="200"
        v-if="pathData.includes('Renew:edit') || pathData.includes('Renew:del')"
      >
        <template #default="scope">
          <Button
            class="mRight-10"
            size="small"
            type="info"
            @click="editAn(scope.row.id)"
            v-if="pathData.includes('Renew:edit')"
            >编辑</Button
          >

          <Poptip
            :transfer="true"
            confirm
            title="确认删除吗?"
            @on-ok="removeAn(scope.row.id)"
            placement="bottom"
          >
            <Button type="error" size="small" v-if="pathData.includes('Renew:del')">删除</Button>
          </Poptip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @current-change="ymChange(tableData.current)"
      v-model:current-page="tableData.current"
      background
      layout="prev, pager, next"
      :total="parseInt(tableData.total)"
    />
  </div>

  <!-- 抽屉 -->
  <Drawer
    v-if="tableData"
    title="编辑"
    :mask-closable="false"
    v-model="DrawerStzte"
    :width="100"
    @on-close="clearChouti"
  >
    <div style="display: flex; margin-bottom: 20px">
      <label for="" style="width: 100px">更新内容：</label>
      <!--  <Input
        v-model="chouti.content"
        size="large"
        placeholder="更新内容"
        type="textarea"
        show-word-limit
      /> -->

      <MdEditor
        v-model="chouti.content"
        :toolbars="toolbars"
        @onUploadImg="onUploadImg"
        previewTheme="smart-blue"
      >
        <template #defToolbars>
          <Emoji />
        </template>
      </MdEditor>
    </div>

    <div style="display: flex; padding-bottom: 20px">
      <label for="" style="width: 90px">更新时间：</label>
      <DatePicker type="date" placeholder="更新时间" v-model="chouti.turnoverTime" />
    </div>

    <div style="display: flex">
      <label for="" style="width: 90px">圆圈颜色：</label>
      <ColorPicker v-model="chouti.type" />
    </div>

    <div style="position: absolute; bottom: 30px; right: 50px">
      <Button type="primary" style="width: 100px" size="large" @click="TiJiao">提交</Button>
      <Button style="margin-left: 20px" size="large" @click="gbct">取消</Button>
    </div>
  </Drawer>
</template>
<script setup>
  const axios = inject('axios');
  import { Notice } from 'view-ui-plus';
  import { eventBus } from '../js/eventBus.js';

  import { MdEditor } from 'md-editor-v3';
  import 'md-editor-v3/lib/style.css';
  import { toolbars } from '../js/toolbars';
  import { Emoji } from '@vavt/v3-extension';
  import '@vavt/v3-extension/lib/asset/style.css';

  const tableWidth = inject('tableWidth'); //表格宽度
  const pathData = inject('pathData'); //拥有的按钮

  const imageList1 = ref([]); //已上传的所有文件
  // 上传图片的配置
  const onUploadImg = async (files, callback) => {
    const res = await Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          const form = new FormData();
          form.append('file', file);

          axios
            .post(variable.pz_all.value.upload_url + '/uploadImg', form, {
              headers: {
                'Content-Type': 'multipart/form-data',
              },
            })
            .then((res) => {
              if (res.data.code == 200) {
                rev(res.data.data);

                //插入到集合中
                imageList1.value.push(res.data.data);
              } else {
                Notice.error({
                  title: '上传失败',
                  desc: error,
                });
              }
            })
            .catch((error) => rej(error));
        });
      }),
    );

    callback(res);
  };

  //刷新
  const refresh = () => {
    //先重置搜索框数据
    content.value = null;
    //调用查询
    findlist(1);
  };

  const DrawerStzte = ref(false); //抽屉状态
  const content = ref(null); //搜索框内容
  const tableData = ref({
    //列表数据
    records: [],
    total: 0,
    current: 1,
  });
  const chouti = ref({
    //抽屉内数据
    id: 0,
    content: '',
    turnoverTime: '',
    type: '',
  });

  //清空抽屉内数据
  function clearChouti() {
    chouti.value.id = 0;
    chouti.value.content = '';
    chouti.value.turnoverTime = '';
    chouti.value.type = '';
    imageList1.value = [];
  }

  onMounted(() => {
    // 调用查询列表
    findlist(1);
    //调用查询图片上传前缀，确保地址没问题
    eventBus.emit('getImgUploadPrefix');
  });

  // 查询列表函数
  function findlist(pageNum) {
    axios
      .post('renew/getRenew', {
        pageNum: pageNum,
        content: content.value,
      })
      .then((response) => {
        let res = response.data;
        if (res.msg == '成功') {
          tableData.value.records = res.data.records;
          tableData.value.total = res.data.total;
          tableData.value.current = res.data.current;
        }
      })
      .catch();
  }

  //页码改变
  function ymChange(pageNum) {
    findlist(pageNum);
  }

  //编辑按钮
  function editAn(id) {
    axios
      .post('renew/getRenew', { id: id })
      .then((response) => {
        let res = response.data;
        if (res.msg == '成功') {
          DrawerStzte.value = true; //打开抽屉
          chouti.value = res.data.records[0];
        } else {
          Notice.error({
            title: res.msg,
          });
        }
      })
      .catch();
  }

  //删除按钮
  function removeAn(id) {
    axios
      .post('renew/delRenew', { id: id })
      .then((response) => {
        let res = response.data;
        if (res.msg == '成功') {
          findlist(tableData.value.current);
          Notice.success({
            title: '删除成功',
          });
        } else {
          Notice.error({
            title: res.msg,
          });
        }
      })
      .catch();
  }

  //编辑中提交按钮
  function TiJiao() {
    if (chouti.value.id == 0) {
      //新增
      axios
        .post('renew/addRenew', chouti.value)
        .then((response) => {
          let res = response.data;
          if (res.msg == '成功') {
            Notice.success({
              title: '新增成功！',
            });
            DrawerStzte.value = false; //关闭抽屉
            findlist(tableData.value.current); // 调用查询列表
            clearChouti(); //清空抽屉数据
          } else {
            Notice.error({
              title: res.msg,
            });
          }
        })
        .catch();
    } else {
      //修改
      axios
        .post('renew/updRenew', chouti.value)
        .then((response) => {
          let res = response.data;
          if (res.msg == '成功') {
            Notice.success({
              title: '修改成功！',
            });
            DrawerStzte.value = false; //关闭抽屉
            findlist(tableData.value.current); // 调用查询列表
            clearChouti(); //清空抽屉数据
          } else {
            Notice.error({
              title: res.msg,
            });
          }
        })
        .catch();
    }
  }

  //关闭抽屉
  function gbct() {
    DrawerStzte.value = false; //关闭抽屉
    //删除已上传的文件
    if (chouti.value.id == 0) {
      axios
        .post('oss/delFiles', imageList1.value)
        .then((response) => {})
        .catch();
    }
    clearChouti();
  }
</script>
<style scoped>
  .main {
    background-color: #fff;
    padding: 15px;
    display: flex;
    flex-direction: column;
  }

  .main_top {
    display: flex;
    justify-content: space-between;
  }
</style>
